﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ProductDemo.Infrastructure;

public class ProductController : Controller
{
    private readonly ApplicationDbContext _context;

    public ProductController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<IActionResult> Index(string productName, string sortOrder, int pageNumber = 1)
    {
        ViewData["CurrentFilter"] = productName;

        var products = from p in _context.Products select p;

        if (!string.IsNullOrEmpty(productName))
        {
            products = products.Where(p => p.ProductName.Contains(productName));
        }

        products = sortOrder == "price_desc" ? products.OrderByDescending(p => p.Price) : products.OrderBy(p => p.Price);


        int pageSize = 10;
        var pagedProducts = await products.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();

        ViewBag.TotalCount = await products.CountAsync();
        ViewBag.CurrentPage = pageNumber;

        return View(pagedProducts);
    }
}